<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>表格渲染</title>
  <style>
    table {
      width: 300px;
      height: 150px;
      text-align: center;
      border: 3px solid red;
    }
  </style>
</head>

<body>
  <table border="3" cellspacing="0" align="center">
    <thead>
      <tr>
        <th>学号</th>
        <th>姓名</th>
        <th>年龄</th>
        <th>性别</th>
      </tr>
    </thead>
  </table>
  <script>
    var userList = [
      { id: 1, name: 'Jack', age: 18, gender: '男' },
      { id: 2, name: 'Rose', age: 20, gender: '女' },
      { id: 3, name: 'Tom', age: 22, gender: '男' },
      { id: 4, name: 'Jerry', age: 24, gender: '女' },
    ];
    // 获取到表格
    var tableEl = document.querySelector("table");

    for (var item of userList) {
      // 根据数组的长度创建对应的行数tr
      var trEl = document.createElement("tr");
      // 遍历数组中的对象，根据对象属性的个数创建对应的td
      for (var key in item) {
        var tdEl = document.createElement("td");
        // 将对象属性的值分别插入对应的td
        tdEl.textContent = item[key];
        // 将td插入到对应的tr中
        trEl.append(tdEl);
      }
      // 将创建tr元素加入到表格中
      tableEl.append(trEl);
    }

    // for (var item of userList) {
    //   var trEl = document.createElement("tr");
    //   trEl.innerHTML = `
    //   <td>${item.id}</td>
    //   <td>${item.name}</td>
    //   <td>${item.age}</td>
    //   <td>${item.gender}</td>
    //   `
    //   tableEl.append(trEl);
    // }

  </script>
</body>

</html>